<?php
/**
 * Notes: 好友模型
 * Created by PhpStorm.
 * Author: TS
 * Date: 2019/9/30
 * Time: 9:36
 */

namespace app\model;


use think\Model;

class Friends extends Model
{
    protected $table = "friends";
    protected $pk = "friend_id";
    public function users(){
        return $this->belongsTo('Users','user_id','user_id');
    }
    public function friendgroup(){
        return $this->belongsToMany('FriendGroup');
    }
    public function moveDefalut($group_id,$default_group_id){
        return self::update([
            'friend_group' => $default_group_id
        ],[
            'friend_group' => $group_id
        ]);
    }
    public function addFriend($data){
        $res = self::create($data);
        return $res;
    }
    public function check($user_id,$friend_target){
        return self::where([
            "user_id" => $user_id,
            "friend_target" => $friend_target
        ])->count();
    }
    public function checkFriendCard($user_id,$friend_target){
        return self::get([
            "user_id" => $user_id,
            "friend_target" => $friend_target
        ]);
    }
    public function checkFriend($user_id,$friend_id){
        return self::where([
            "user_id" => $user_id,
            "friend_target" => $friend_id
        ]);
    }
    public function del($friend_id){
        return self::get($friend_id) -> delete();
    }
    public function delByFriend($user_id,$friend_target){
        return self::where([
            "user_id" => $user_id,
            "friend_target" => $friend_target
        ])->delete();
    }
    public function getGroupFriend($friend_group_id){
        return self::join('users','friends.friend_target = users.user_id')
            ->where(['friend_group' => $friend_group_id])
            ->field(['friends.friend_target','friend_id','friend_group','user_name','user_header','user_info','role_id','friend_alias'])
            ->select();
    }
    public function getById($friend_id){
        return self::get($friend_id);
    }
    public function edit($user_id,$friend_target,$data){
        return self::update($data,[
            "user_id" => $user_id,
            "friend_target" => $friend_target
        ]);
    }
}